import React, { Component } from 'react'
import { Menu } from 'antd';
import { Link, withRouter } from "react-router-dom"
import { connect } from "react-redux"
import { createSaveTitleAction } from "../../../redux/actions/leftNav_action"
import menuArr from '../../../config/menu_config';
import logo from "../../../static/imgs/logo.png"
import "./css/left_nav.less"
const { SubMenu } = Menu;

class LeftNav extends Component {
    save_title = (value) => {
        this.props.saveTitle(value)
    }
    //用于创建菜单的函数
    createMenu = (tartget) => {
        return tartget.map((item) => {
            //先判断是否有权限
            if(this.hasAuth(item)) {
                if (!item.children) {
                    return (
                        <Menu.Item onClick={() => { this.save_title(item.title) }} key={item.key} icon={item.icon}>
                            <Link to={item.pathname}>
                                {item.title}
                            </Link>
                        </Menu.Item>
                    )
                } else {
                    return (
                        <SubMenu key={item.key} icon={item.icon} title={item.title}>
                            {this.createMenu(item.children)}
                        </SubMenu>
                    )
                }
            }

        })

    }
    //判断是否有权限，有权限------>true;  没权限------->false   【这里逻辑不太明白】
    hasAuth = (item)=>{
        const {menus,username} = this.props
        if(username === "admin") return true
        else if(!item.children) {
            return menus.find((item2)=>{return item2 === item.key})
        } else if (item.children) {
            return item.children.some((item3)=>{return menus.indexOf(item3.key) !== -1})
        }
    }

    render() {
        const {pathname} = this.props.location
        return (
            <div>
                <header className='nav-header'>
                    <img alt='logo' src={logo} />
                    <h1>商品管理系统</h1>
                </header>
                <Menu
                    selectedKeys={pathname.indexOf('product') !== -1 ? 'product': pathname.split('/').reverse()[0]}
                    defaultOpenKeys={pathname.split('/').splice(2)}
                    mode="inline"
                    theme="dark"
                >

                    {this.createMenu(menuArr)}

                </Menu>
            </div>
        )
    }
}
let a = withRouter(LeftNav)
export default connect(
    state => ({
        menus:state.userInfo.user.role.menus,
        username:state.userInfo.user.username
    }),
    { saveTitle: createSaveTitleAction }
)(a)   
